import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import router from './router';
import { useUserStore } from '@/stores/userStore';


import '@fortawesome/fontawesome-free/css/all.css';
import '@fortawesome/fontawesome-free/css/fontawesome.min.css';
//自定义全局样式
import '@/assets/style.css';


const app = createApp(App)
const pinia = createPinia();

// 在axios实例或全局axios中添加
axios.interceptors.request.use(config => {
  const store = useUserStore();
  // 动态判断是否需要认证
  if (store.isLoggedIn && config.requiresAuth !== false) {
    config.headers.Authorization = `Bearer ${store.authToken}`;
  } else {
    // 确保不携带失效token
    delete config.headers.Authorization;
  }
  return config;
});
// 创建axios实例时添加CSRF处理
const instance = axios.create({
  withCredentials: true, // 允许携带cookie
  headers: {
    'X-CSRFToken': localStorage.getItem('csrftoken') || ''
  }
})

// 添加响应拦截器处理CSRF过期
instance.interceptors.response.use(
  response => response,
  async error => {
    if (error.response?.status === 403 && error.config.url !== '/api/accounts/get_csrf_token/') {
      const userStore = useUserStore()
      await userStore.fetchCSRFToken()
      error.config.headers['X-CSRFToken'] = userStore.csrfToken
      return instance.request(error.config)
    }
    return Promise.reject(error)
  }
)


app.use(pinia)
app.use(router)
app.mount('#app')

// 在应用启动时检查登录状态
